#include "qKalkulacijalista.h"
#include <QSqlQuery>
#include <QSqlRecord>
#include <QDesktopWidget>


QKalkulacijaLista::QKalkulacijaLista(QWidget *parent)
	: QMyBaseFormWidget(parent)
{
	ui.setupUi(this);
	QDesktopWidget desk;
	QRect deskRect = desk.screenGeometry();
	ui.layoutWidget->setFixedWidth(deskRect.width() - 300);
	ui.layoutWidget->setFixedHeight(deskRect.height()-200);

	ui.tableView->setSelectionMode(QAbstractItemView::SingleSelection);
	ui.tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
	ui.tableView_2->setSelectionMode(QAbstractItemView::SingleSelection);
	ui.tableView_2->setSelectionBehavior(QAbstractItemView::SelectRows);

	ui.tableView->setSortingEnabled(true);
	connect(ui.tableView->horizontalHeader(),SIGNAL(sectionClicked(int)), ui.tableView, SLOT(sortByColumn(int)));
	ui.tableView_2->setSortingEnabled(true);
	connect(ui.tableView_2->horizontalHeader(),SIGNAL(sectionClicked(int)), ui.tableView_2, SLOT(sortByColumn(int)));

	lista("%%%");
	m_selectedText = model->item(0, 0) ? model->item(0, 0)->text():"";
	lista_detail(m_selectedText);
	ui.tableView->setFocus();
}


QKalkulacijaLista::~QKalkulacijaLista()
{

}

void QKalkulacijaLista::lista(const QString& nameSearch)
{
    if (nameSearch.length() < 0)
    {
        ui.tableView->hide();
        return;
    }
    int r = 0;
    int c = 14;
    int fieldNo[14];
    QString country[14];
    int colWidth[] = {0, 50, 60, 200, 100, 100, 100, 100, 100, 100, 100, 100, 50, 0};
    QString colName[] = {"id", "dok_id", "datum", "naziv", "adresa", "grad", "opis"};
	QString temp = 
	"select kalkulacii.id, dok_id, datum, komintenti.naziv, kalkulacii.carina, kalkulacii.transport, kalkulacii.drugi_trosoci, kalkulacii.dok_opis, kalkulacii.iznos_faktura, kalkulacii.kurs, kalkulacii.valuta, kalkulacii.danok, kalkulacii.rabat, kalkulacii.prevoznik_id "
	"from kalkulacii "
	"left join komintenti on kalkulacii.komintent_id = komintenti.id "
	"order by dok_id desc "
    ;
    QSqlQuery query(temp);
    model = new QStandardItemModel(r,c);
    model->setHeaderData( 0, Qt::Horizontal, trUtf8("Id."));
    model->setHeaderData( 1, Qt::Horizontal, trUtf8("Бр."));
    model->setHeaderData( 2, Qt::Horizontal, trUtf8("Датум"));
	model->setHeaderData( 3, Qt::Horizontal, trUtf8("Назив"));
    model->setHeaderData( 4, Qt::Horizontal, trUtf8("Царина"));
    model->setHeaderData( 5, Qt::Horizontal, trUtf8("Транспорт"));
    model->setHeaderData( 6, Qt::Horizontal, trUtf8("Други трошоци"));
	model->setHeaderData( 7, Qt::Horizontal, trUtf8("Опис"));
	model->setHeaderData( 8, Qt::Horizontal, trUtf8("Износ Фактура"));
	model->setHeaderData( 9, Qt::Horizontal, trUtf8("Курс"));
	model->setHeaderData( 10, Qt::Horizontal, trUtf8("Валута"));
	model->setHeaderData( 11, Qt::Horizontal, trUtf8("Данок"));
	model->setHeaderData( 12, Qt::Horizontal, trUtf8("Рабат"));
	model->setHeaderData( 12, Qt::Horizontal, trUtf8("ПревозникИд"));
	ui.tableView->setModel(model);
    header = new QHeaderView(Qt::Horizontal, this);
	header->setClickable(true);
    ui.tableView->setHorizontalHeader(header);
    header->show();
    int row = 0;
    while (query.next()) 
    {
        for (int i = 0; i < c; i++)
        {
			QString temp = query.value(i).toString();
			if (i == 2)
            {
				temp = temp.left(10);
				QStandardItem *item = new QStandardItem(temp);
				item->setEditable(false);
				ui.tableView->setRowHeight(row, 18);
				ui.tableView->setColumnWidth(i, colWidth[i]);
				model->setItem(row, i, item);
            }

			else if ((i == 4)||(i == 5)||(i == 6)||(i == 8)||(i == 9)||(i == 11)||(i == 12))
			{
				QLocale loc;
				temp =  loc.toString(temp.toFloat(), 'f', 2);
				QStandardItem *item = new QStandardItem(temp);
				item->setTextAlignment(Qt::AlignRight);
				item->setEditable(false);
				ui.tableView->setRowHeight(row, 18);
				ui.tableView->setColumnWidth(i, colWidth[i]);
				model->setItem(row, i, item);
			}
			else
			{
				QStandardItem *item = new QStandardItem(temp);
				item->setEditable(false);
				ui.tableView->setRowHeight(row, 18);
				ui.tableView->setColumnWidth(i, colWidth[i]);
				model->setItem(row, i, item);
			}
        }
        row++;
    } 
	QItemSelectionModel *sm = ui.tableView->selectionModel();
	connect(sm, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
		this, SLOT(selectionChanged(QModelIndex,QModelIndex)));
	ui.tableView->show();
}
void QKalkulacijaLista::selectionChanged(QModelIndex modelX, QModelIndex modelY)
{
	QLocale loc;
	int i = modelX.row();
	m_selectedText = model->item(i, 1) ? model->item(i, 1)->text():"";
    float carina = loc.toFloat(model->item(i, 4)->text());
	float transport = loc.toFloat(model->item(i, 5)->text());
	float dr_trosoci = loc.toFloat(model->item(i, 6)->text());

	float iznos_faktura = loc.toFloat(model->item(i, 8)->text());
	float kurs = loc.toFloat(model->item(i, 9)->text());
	float danok = loc.toFloat(model->item(i, 11)->text());
	float rabat = loc.toFloat(model->item(i, 12)->text());

	QString t = model->item(i, 7)->text();
    ui.textEdit->setPlainText(model->item(i, 7)->text());

	ui.lineEdit->setText(loc.toString( carina, 'f', 2));
	ui.lineEdit_2->setText(loc.toString( transport, 'f', 2));
	ui.lineEdit_3->setText(loc.toString( dr_trosoci, 'f', 2));
	ui.lineEdit_4->setText(loc.toString( m_sumaIznosStavki, 'f', 2));
	ui.lineEdit_5->setText(loc.toString( iznos_faktura * kurs * (100.f - rabat) / 100.f + carina + transport +dr_trosoci, 'f', 2));

	ui.lineEdit_6->setText(loc.toString( iznos_faktura, 'f', 2));
	ui.lineEdit_7->setText(loc.toString( kurs, 'f', 2));
	ui.lineEdit_9->setText(loc.toString( danok, 'f', 2));
    ui.lineEdit_8->setText(model->item(i, 10)->text());
    ui.lineEdit_10->setText(model->item(i, 12)->text());

    lista_detail(m_selectedText);

	m_kalkulacija_id = model->item(i, 1)->text();
	m_kalkulacija_datum = model->item(i, 2)->text();
	m_komintent_naziv = model->item(i, 3)->text();
	m_iznos = model->item(i, 8)->text();
	m_iznos_ddv = model->item(i, 11)->text();
	m_iznos_1 = ui.lineEdit_5->text(); //  iznos_faktura * kurs * (100.f - rabat) / 100.f + carina + transport +dr_trosoci
	m_iznos_2 = loc.toString( iznos_faktura * kurs * (100.f - rabat) / 100.f , 'f', 2);;
	m_iznos_3 = loc.toString(transport, 'f', 2);  //  transport
 	m_iznos_4 = loc.toString( carina + danok , 'f', 2);  //  danok + carina
	m_iznos_5 = loc.toString( danok , 'f', 2);  //  danok
	m_iznos_6 = loc.toString( iznos_faktura * kurs * (100.f - rabat) / 100.f + carina + transport +dr_trosoci + danok, 'f', 2); // iznos
	m_komintent_naziv = model->item(i, 13)->text();
	
}
void QKalkulacijaLista::lista_detail(const QString& nameSearch)
{
	QLocale loc;
    if (nameSearch.length() < 0)
	{
		ui.tableView_2->hide();
		return;
	}

	float kurs = loc.toFloat(ui.lineEdit_7->text());
	float vkIznosFaktura = loc.toFloat(ui.lineEdit_6->text());

	float carina = loc.toFloat(ui.lineEdit->text());
	float transport = loc.toFloat(ui.lineEdit_2->text());
	float drTrosoci = loc.toFloat(ui.lineEdit_3->text());
	float rabat = loc.toFloat(ui.lineEdit_10->text());
	float kRbt = (100.f - rabat) / 100.f;
	vkIznosFaktura = vkIznosFaktura * kRbt;

	float vkIznosTrosoci = carina + transport + drTrosoci;
	float raspTrosoci = 0;
	if (vkIznosFaktura * kurs)
	{
		raspTrosoci = (vkIznosFaktura * kurs + vkIznosTrosoci)/(vkIznosFaktura * kurs );
	}

	int r = 0;
	int c = 10;
	int fieldNo[10];
	QString country[10];
	int colWidth[] = {40, 70, 220, 60, 80, 80, 80, 80, 80, 80};
	QString colName[] = {"id", "sifra", "artikal", "edm", "ikol", "icena", "mag_id" };
	QString temp = 
		"select artikli.id, sifra, artikal, edm, ikol, icena "
		"from kalkulacii_stavki "
		"left join artikli on kalkulacii_stavki.artikal_id=artikli.id "
		"where  kalkulacii_stavki.dok_id= ";
	temp += nameSearch;
	QSqlQuery query(temp);
	model2 = new QStandardItemModel(r,c);
	model2->setHeaderData( 0, Qt::Horizontal, trUtf8("Ид."));
	model2->setHeaderData( 1, Qt::Horizontal, trUtf8("Шифра"));
	model2->setHeaderData( 2, Qt::Horizontal, trUtf8("Артикал"));
	model2->setHeaderData( 3, Qt::Horizontal, trUtf8("Едм."));
	model2->setHeaderData( 4, Qt::Horizontal, trUtf8("Количина"));
	model2->setHeaderData( 5, Qt::Horizontal, trUtf8("Е.Цена.Вал."));
	model2->setHeaderData( 6, Qt::Horizontal, trUtf8("Е.Цена.Ден."));
	model2->setHeaderData( 7, Qt::Horizontal, trUtf8("Е.Трошоци"));
	model2->setHeaderData( 8, Qt::Horizontal, trUtf8("Е.Наб.Цена"));
	model2->setHeaderData( 9, Qt::Horizontal, trUtf8("Вк.Износ"));

	ui.tableView_2->setModel(model2);
	header = new QHeaderView(Qt::Horizontal, this);
	header->setClickable(true);
	ui.tableView_2->setHorizontalHeader(header);
	header->show();
	int row = 0;
	m_sumaIznosStavki = 0;
	m_sumaTrosoci = 0;
	while (query.next()) 
	{
		int row = model2->rowCount();
		for (int i = 0; i < c; i++)
		{
			QStandardItem *item = NULL;
			QString temp = "";

			if ((i > 3) && (i < 6))
			{
				temp = query.value(i).toString();
				temp =  loc.toString(temp.toFloat(), 'f', 2);
				item = new QStandardItem(temp);
				item->setTextAlignment(Qt::AlignRight);
			}
			else if(i <= 3)
			{
				temp = query.value(i).toString();
				item = new QStandardItem(temp);
				item->setTextAlignment(Qt::AlignLeft);
			}
			else 
			{
				if (i == 6) // edinecna cena denari
				{
					temp = query.value(5).toString();
					temp =  loc.toString(temp.toFloat() * kurs * kRbt, 'f', 2);
					item = new QStandardItem(temp);
					item->setTextAlignment(Qt::AlignRight);
				}
				if (i == 7) // edinecni trosoci
				{
					temp =  loc.toString( query.value(5).toFloat() * kurs * kRbt * (raspTrosoci- 1), 'f', 2);
					item = new QStandardItem(temp);
					item->setTextAlignment(Qt::AlignRight);
				}

				if (i == 8) // edinecna nabavna cena
				{
					temp = query.value(5).toString();
					temp =  loc.toString(temp.toFloat()  * kurs * kRbt * raspTrosoci, 'f', 2);
					item = new QStandardItem(temp);
					item->setTextAlignment(Qt::AlignRight);
				}

				if (i == 9) // vk iznos
				{
					temp =  loc.toString(query.value(4).toFloat() * query.value(5).toFloat() * kurs * kRbt * raspTrosoci, 'f', 2); // kol * cena vo valuta
					item = new QStandardItem(temp);
					item->setTextAlignment(Qt::AlignRight);
					m_sumaIznosStavki += query.value(4).toFloat() * query.value(5).toFloat() * kurs * kRbt * raspTrosoci;
				}
			}

			item->setEditable(false);
			ui.tableView_2->setRowHeight(row, 18);
			ui.tableView_2->setColumnWidth(i, colWidth[i]);
			model2->setItem(row, i, item);
		}        
	} 
	ui.lineEdit_4->setText(loc.toString( m_sumaIznosStavki, 'f', 2));

	ui.tableView_2->show();
}

void QKalkulacijaLista::pressEscape()
{
	emit closeW();
}

void QKalkulacijaLista::deleteDok(int idDok)
{
//     QString temp = "select id from kalkulacii where dok_tip = 20 and dok_id =";
//     temp += QString::number(idDok);
//     QSqlQuery query(temp);
//     QString country = "";
//     while (query.next()) {
//         country = query.value(query.record().indexOf("id")).toString();
//     }
// 
//     query.clear();
//     query.prepare("delete from kalkulacii_stavki where dok_id = :a");
//     query.bindValue(":a", idDok);	
//     query.exec();
}


void QKalkulacijaLista::on_pushButton_clicked()
{
    emit procF2();
}
void QKalkulacijaLista::on_pushButton_2_clicked()
{
    emit procF3();
}
QStringList QKalkulacijaLista::geInfo()
{
    QStringList info;
    info.clear();
//    info << ui.lineEdit_3->text() << ui.lineEdit_4->text() << ui.lineEdit_5->text() << ui.lineEdit->text() << ui.lineEdit_2->text(); 
    return info;
}

int QKalkulacijaLista::getRow()
{
	int m_row = -1;
	QModelIndexList indexes = ui.tableView->selectionModel()->selection().indexes();
	if (indexes.count())
	{
		m_row = indexes.at(0).row();
	}
	return m_row;
}

void QKalkulacijaLista::setRow(int mrow)
{
	ui.tableView->selectRow(mrow);
	ui.tableView->setFocus();
}
void QKalkulacijaLista::pressReturn()
{
	if (ui.tableView->hasFocus())
	{
		izlFakturaData mData;
		mData.faktura_id = m_kalkulacija_id;
		mData.faktura_datum = m_kalkulacija_datum;
		mData.faktura_komintent = "";
		mData.faktura_komintent_id = m_komintent_naziv;
		mData.faktura_iznos = m_iznos;
		mData.faktura_ddv = m_iznos_ddv;


		mData.faktura_iznos_1 = m_iznos_1;  
		mData.faktura_iznos_2 = m_iznos_2;   
		mData.faktura_iznos_3 = m_iznos_3;  
		mData.faktura_iznos_4 = m_iznos_4;  
		mData.faktura_iznos_5 = m_iznos_5;  

		// 	m_iznos_5 = ;
		
		mData.faktura_vkupenIznos = "";
		mData.faktura_valuta = m_kalkulacija_datum;
		emit sFakturiToIzvod(ui.lineEdit_6->text(), ui.lineEdit_8->text(), ui.lineEdit_9->text(), m_selectedText, mData);	
	}
}